/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.src.xyzk.bluetooth;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.src.tsdl_personal.R;
import com.src.xyzk.bluetooth.service.BluetoothAdapterService;
import com.src.xyzk.bluetooth.service.bluetoothClsUtils;
import com.src.xyzk_personal.config.Common;
import com.src.xyzk_personal.config.DiagAlertDialog;

/**
 * This Activity appears as a dialog. It lists any paired devices and
 * devices detected in the area after discovery. When a device is chosen
 * by the user, the MAC address of the device is sent back to the parent
 * Activity in the result Intent.
 */
public class BluetoothDeviceListActivity extends Activity{
	// Debugging
	private static final String TAG = "BluetoothDeviceListActivity";
	private static final boolean D = false;
	Context context = BluetoothDeviceListActivity.this;

	public static final int RESULT_OK = 1; //返回值OK
	public static final int RESULT_FAIL = 0; //返回值失败
	//Handler更新消息
	public static final int HAND_UPDATE_LIST = 101; //更新蓝牙已经配对列表
	public static final int HAND_ADD_LIST=102;	  //蓝牙新增列表
	public static final int HAND_UPDATE_AND_SEARCH = 103; //更新列表并开始查找蓝牙
	public static final int HAND_UPDATE_BAUND_BLUETOOTH = 104; //更新已经配对的蓝牙状态
	public static final int HAND_CHANGE_BLUETOOTH_NAME = 105; //蓝牙改名消息
	public static final int HAND_UPDATE_BLUETOOTH_STATE = 106; //设置蓝牙连接状态
	public static final int HAND_RECEIVE_CONNECT	=	107;	//接收蓝牙连接消息
	public static final int HAND_AUTO_CONNECT_BLUETOOTH = 108;	//自动连接蓝牙
	public static String EXTRA_DEVICE_ADDRESS = "device_address"; //put的蓝牙句柄

	//蓝牙连接状态
	public static final int BLUE_None = 1; 			//未连接
	public static final int BLUE_Connecting = 2; 	//正在连接..
	public static final int BLUE_Connected = 3;		//已经连接成功
	public static final int BLUE_Connectfail = 4;	//连接失败

	// Return Intent extra
	//public static String EXTRA_DEVICE_ADDRESS = "device_address";
	//button 返回、开关、查找
	Button m_but_reurn,m_but_open,m_but_search;
	//注册ListView操作变量
	private ListView m_listview = null;
	//注册List适配器
	private DeviceListAdapter m_listadapter = null;
	//List数据源
	private List<HashMap<String,Object>> m_listdata = new ArrayList<HashMap<String,Object>>();
	//获取系统蓝牙设备
	private BluetoothAdapter m_BluetoothAdapter = null;
	//打开蓝牙进度条
	private ProgressDialog progressdiag;
	//UI更新Handler
	public MyHandler m_handler = null;
	//当前连接蓝牙列表序号
	int m_nowItem = 0;
	//初始化连接service//蓝牙服务
	BluetoothAdapterService m_bluttoothservice = BluetoothAdapterService.getInstance();
	//test
	private int m_test = 0;
	@Override
	protected synchronized void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Setup the window
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.bluetooth_device_list);
		//初始化返回值
		setResult(Activity.RESULT_CANCELED);
		//添加进度条
		progressdiag = new ProgressDialog(this);
		progressdiag.setMessage(getResources().getText(
				R.string.bluetoothconnect_open).toString());
		// 初始化界面控件
		//初始化handler
		m_handler = new MyHandler();
		//初始化返回按钮
		m_but_reurn = (Button) findViewById(R.id.bluetoothconnect_button_return);
		m_but_reurn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//m_blue_data_service.SetShowConnectActivity(false);
				Intent intent = getIntent();
				setResult(RESULT_FAIL,intent);
				finish();
			}
		});
		//初始化重置蓝牙按钮
		m_but_open = (Button) findViewById(R.id.bluetoothconnect_button_open);
		m_but_open.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// 等待 蓝牙打开结束
				if(m_bluttoothservice.m_blue_state.IsConnected())
					m_bluttoothservice.StopService();
				new StopProgressdiag().start();
				progressdiag.show();
			}
		});
		//初始化查询按钮
		m_but_search = (Button) findViewById(R.id.bluetoothconnect_button_search);
		m_but_search.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//先清除未配对蓝牙列表
				//发消息更新列表
				Message msg = m_handler.obtainMessage(HAND_UPDATE_LIST,HAND_UPDATE_AND_SEARCH,0);
				m_handler.sendMessage(msg);
			}
		});
		//初始化listview
		m_listview = (ListView)findViewById(R.id.bluetoothconnect_listview);
		m_listadapter = new DeviceListAdapter(m_listdata); //初始化adapter
		m_listview.setAdapter(m_listadapter);//绑定adapter和listview
		//添加list点击事件
		m_listview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
									long arg3) {
				// TODO Auto-generated method stub
				//取得点击对象ITEM
				DeviceList holder = (DeviceList)arg1.getTag();
				//点击开始建立连接或者进行配对
				if(D) Log.i(TAG,"name=" + holder.Pdevice_name.getText().toString() +
						"Mac= " + holder.Pdevice_mac.getText().toString() +
						";  pair= " + holder.Pdevice_pair.getText().toString());
				//增加对蓝牙打开的判断
				if(m_BluetoothAdapter.isEnabled() == false)
				{
					DiagAlertDialog dlg = new DiagAlertDialog(BluetoothDeviceListActivity.this);
					dlg.setMessage(R.string.bluetoothconnect_tip_bluecancel);
					dlg.setPositiveButton(R.string.but_ok, new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							Intent intent = getIntent();
							setResult(RESULT_FAIL,intent);
							finish();
						}
					});
					dlg.show();
					return;
				}
				//先取消搜索
				if(m_BluetoothAdapter.isDiscovering())
					m_BluetoothAdapter.cancelDiscovery();
				m_but_search.setClickable(true);
				m_but_search.setText(R.string.bluetoothconnect_button_search);
				//先检查MAC地址是否正确
				String address = holder.Pdevice_mac.getText().toString();
				if(address.length() != 17)
				{
					//提示版本不匹配，请升级
					Toast.makeText(context, context.getString(R.string.bluetoothconnect_mac_error),
							Toast.LENGTH_SHORT).show();
					return;
				}
				BluetoothDevice btdev = m_BluetoothAdapter.getRemoteDevice(holder.Pdevice_mac.getText().toString());
				if(btdev.getBondState() != BluetoothDevice.BOND_BONDED) //未配对就配对
				{
					try {
						bluetoothClsUtils.createBond(btdev.getClass(), btdev);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				//设置连接状态
				m_nowItem = arg2;
				SetListBluetoothconnectState(m_nowItem,BLUE_Connecting);
				CheckBluetoothBox(holder.Pdevice_name.getText().toString(),address);
			}
		});
		//长按listview效果
		m_listview.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void onCreateContextMenu(ContextMenu menu, View v,
											ContextMenuInfo menuInfo) {
				// TODO Auto-generated method stub
				AdapterContextMenuInfo menuInfo1 = (AdapterContextMenuInfo)menuInfo;
				int pos = (int)m_listadapter.getItemId(menuInfo1.position);
				HashMap<String, Object> now = null; //数据源
				now = (HashMap<String, Object>) m_listadapter.getItem(pos);

				menu.setHeaderTitle(now.get("device_name").toString());
				int i = 0;
				BluetoothDevice device = m_BluetoothAdapter.getRemoteDevice(now.get("device_mac").toString());
				if(device.getBondState() == BluetoothDevice.BOND_BONDED) //只有已经配对的菜添加取消配对按钮
					menu.add(0,i++,0,R.string.bluetoothconnect_set_cancelpair);
				menu.add(0,i++,0,R.string.bluetoothconnect_button_return);
			}
		});
		// 注册这蓝牙查找BroadcastReceiver
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
		filter.addAction(BluetoothDevice.ACTION_NAME_CHANGED);
		filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
		filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
		filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		registerReceiver(m_bluetoothReceiver, filter);
		//初始化蓝牙
		m_BluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		//判断是否有蓝牙设备
		if(m_BluetoothAdapter == null)
		{
			if(D) Log.i(TAG,"无蓝牙设备!");
			Intent intent = getIntent();
			setResult(RESULT_FAIL,intent);
			finish();
		}
		//启动进度条
		progressdiag.show();
		// 等待 蓝牙打开结束
		new StartblueProgressdiag().start();
	}
	//配对完成，检查是否是我们设置的蓝牙
	void CheckBluetoothBox(String name,String mac)
	{
		//获取蓝牙状态
		//if(Common.BoxName.equals(name)) //同名可以连接
		if(true)
		{
			m_bluttoothservice.Sethandler(m_handler);
			m_bluttoothservice.ConnectDevice(mac); //连接
		}
		else
		{
			Toast.makeText(context, "请连接本设备匹配的蓝牙接头!", Toast.LENGTH_SHORT).show();
			return;
		}
	}
	//自动连接蓝牙方法
	void AutoExeConnectBlue(String Pname,String addr)
	{
		//先判断蓝牙是否打开
		if(m_BluetoothAdapter.isEnabled() == false) return;
		//先取消搜索
		if(m_BluetoothAdapter.isDiscovering())
			m_BluetoothAdapter.cancelDiscovery();
		m_but_search.setClickable(true);
		m_but_search.setText(R.string.bluetoothconnect_button_search);
		//先检查MAC地址是否正确
		String address = addr;
		if(address.length() != 17)
		{
			//提示版本不匹配，请升级
			Toast.makeText(context, context.getString(R.string.bluetoothconnect_mac_error),
					Toast.LENGTH_SHORT).show();
			return;
		}
		BluetoothDevice btdev = m_BluetoothAdapter.getRemoteDevice(address);
		if(btdev.getBondState() != BluetoothDevice.BOND_BONDED) //未配对就配对
		{
			try {
				bluetoothClsUtils.createBond(btdev.getClass(), btdev);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		//设置连接状态
		m_nowItem = 0;
		SetListBluetoothconnectState(m_nowItem,BLUE_Connecting);
		CheckBluetoothBox(Pname,address);
	}
	//启动蓝牙线程
	class StartblueProgressdiag extends Thread {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			try {

				//获取系统蓝牙设备打开状态
				while(true)
				{
					sleep(100);
					if(!m_BluetoothAdapter.isEnabled())
					{
						if(D) Log.i(TAG,"打开蓝牙设备!");
						//不做提示，强行打开
						if(m_BluetoothAdapter.enable() == true)
							break;
					}
					else
					{
						break;
					}
				}
				while(true)
				{
					sleep(500);
					if(m_BluetoothAdapter.isEnabled())
					{
						if (progressdiag.isShowing())
						{
							progressdiag.dismiss();
						}
						if(D) Log.i(TAG,"发消息更新列表!");
						Message msg = m_handler.obtainMessage(HAND_UPDATE_LIST);
						m_handler.sendMessage(msg);
						break;
					}
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//下面是自动执行蓝牙连接程序,先延时等待列表刷新
			try {
				sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//查找列表是否有已经配对的蓝牙设备
			if(m_listdata.size() >= 1) //有已经配对的蓝牙设备,则连接该设备
			{
				m_handler.obtainMessage(HAND_AUTO_CONNECT_BLUETOOTH, 0, 0).sendToTarget();
			}
		}

	}
	//处理按键消息
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch(keyCode)
		{
			case KeyEvent.KEYCODE_BACK:
				//m_blue_data_service.BlueConnectClose();
		}
		return super.onKeyDown(keyCode, event);
	}
	//长按list出现的菜单点击实现方法
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo)item.getMenuInfo();
		int pos = (int)m_listadapter.getItemId(menuInfo.position);
		HashMap<String, Object> now = null; //数据源
		now = (HashMap<String, Object>) m_listadapter.getItem(pos);
		// TODO Auto-generated method stub
		switch(item.getItemId())
		{
			case 0:		//取消配对
				if(D) Log.i(TAG,"取消配对：" + pos);
				BluetoothDevice device = m_BluetoothAdapter.getRemoteDevice(now.get("device_mac").toString());
				try {
					bluetoothClsUtils.removeBond(device.getClass(), device);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			default:
				break;
		}
		return super.onContextItemSelected(item);
	}
	/*********** 设置蓝牙连接提示**********************/
	@SuppressWarnings("unchecked")
	void SetListBluetoothconnectState(int nowItem,int state)
	{
		String v_status = null;
		switch (state)
		{
			case BLUE_None:
				v_status = getString(R.string.bluetoothconnect_blue_connectnone);
				break;
			case BLUE_Connecting:
				v_status = getString(R.string.bluetoothconnect_blue_connecting);
				break;
			case BLUE_Connected:
				v_status = getString(R.string.bluetoothconnect_blue_connected);
				break;
			case BLUE_Connectfail:
				v_status = getString(R.string.bluetoothconnect_blue_connectfail);
				break;
			default:
				break;
		}
		HashMap<String, Object> now = null; //数据源
		now = (HashMap<String, Object>) m_listadapter.getItem(nowItem);
		now.put("device_status", v_status);
		if(m_listadapter != null)
			m_listadapter.notifyDataSetChanged();
	}
	//重置蓝牙线程
	class StopProgressdiag extends Thread {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			try {
				//先关闭蓝牙
				if(m_BluetoothAdapter.isEnabled())
				{
					while(true)
					{
						sleep(500);
						if(m_BluetoothAdapter.disable() == true)
						{
							if(D) Log.i(TAG,"关闭重置蓝牙设备!");
							break;
						}
					}
				}
				//获取系统蓝牙设备打开状态
				while(true)
				{
					sleep(500);
					if(!m_BluetoothAdapter.isEnabled())
					{
						if(D) Log.i(TAG,"打开蓝牙设备!");
						//不做提示，强行打开
						if(m_BluetoothAdapter.enable() == true)
							break;
					}
					else
					{
						break;
					}
				}
				while(true)
				{
					sleep(500);
					if(m_BluetoothAdapter.isEnabled())
					{
						if (progressdiag.isShowing())
						{
							progressdiag.dismiss();
						}
						//发消息更新列表
						Message msg = m_handler.obtainMessage(HAND_UPDATE_LIST);
						m_handler.sendMessage(msg);
						break;
					}
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
	//UI更新Handler
	public class MyHandler extends Handler
	{
		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if(msg.what == HAND_UPDATE_LIST)
			{
				int i;
				//刷新蓝牙已配对列表
				if(D) Log.i(TAG,"清除设备列表!");
				m_listdata.clear(); //先清除LIST
				m_listadapter.notifyDataSetChanged();
				//更新列表
				Set<BluetoothDevice> v_bluetooth_pairedDevices = m_BluetoothAdapter.getBondedDevices();
				for (BluetoothDevice device : v_bluetooth_pairedDevices)
				{
					//增加名字过滤
					if(FilterBluetoothName(device.getName().toString()) == false)
						continue;
					HashMap<String, Object> v_data = new HashMap<String, Object>();
					v_data.put("device_icon", R.drawable.bluetooth_device_default);
					v_data.put("device_name", device.getName());
					//获取当前蓝牙的连接状态
					v_data.put("device_status", getString(R.string.bluetoothconnect_blue_connectnone));
					v_data.put("device_mac", device.getAddress());
					v_data.put("device_pair", getString(R.string.bluetoothconnect_pair));
					m_listdata.add(v_data);
					if(D) Log.i(TAG,"加入已配对设备+" + device.getName());
				}
				m_listadapter.notifyDataSetChanged();
				//判断是否需要查找设备
				if(msg.arg1 == HAND_UPDATE_AND_SEARCH)
				{
					if(D) Log.i(TAG,"查找设备...");
					if (m_BluetoothAdapter.isDiscovering()) {
						m_BluetoothAdapter.cancelDiscovery();
					}
					m_BluetoothAdapter.startDiscovery();
					//屏蔽查找按钮
					m_but_search.setClickable(false);
					m_but_search.setText(R.string.bluetoothconnect_button_searching);
				}
				//关闭滚动条
				if (progressdiag.isShowing())
				{
					progressdiag.dismiss();
				}
			}
			else if(msg.what == HAND_ADD_LIST) //添加未配对的蓝牙列表
			{
				BluetoothDevice device = (BluetoothDevice)msg.obj;
				//增加名字过滤，只显示launch和DBS开头的蓝牙
				if(FilterBluetoothName(device.getName().toString()) == false)
					return;
				//增加重复查找的列表显示，过滤重复的设备名
				if(FilterDuplicateName(m_listdata,device.getAddress().toString()) == true)
					return;
				HashMap<String, Object> v_data = new HashMap<String, Object>();
				v_data.put("device_icon", R.drawable.bluetooth_device_enable);
				v_data.put("device_name", device.getName());
				v_data.put("device_status", getString(R.string.bluetoothconnect_blue_connectnone));
				v_data.put("device_mac", device.getAddress());
				v_data.put("device_pair", getString(R.string.bluetoothconnect_nopair));
				m_listdata.add(v_data);
				if(D) Log.i(TAG,"添加新搜索设备+" + device.getName());
				m_listadapter.notifyDataSetChanged();
			}
			else if(msg.what == HAND_UPDATE_BAUND_BLUETOOTH) //更新已经配对的蓝牙的状态图标
			{
				BluetoothDevice device = (BluetoothDevice)msg.obj;
				//先查找蓝牙位置
				for(int i = 0; i < m_listadapter.getCount(); i ++)
				{
					HashMap<String, Object> now = null; //数据源
					now = (HashMap<String, Object>) m_listadapter.getItem(i);
					if((now.get("device_mac").toString()).equals((device.getAddress().toString())))
					{
						now.put("device_icon", R.drawable.bluetooth_device_enable);
						now.put("device_name", device.getName());
						break;
					}
				}
				m_listadapter.notifyDataSetChanged();
			}
			else if(msg.what == HAND_RECEIVE_CONNECT) //蓝牙连接消息
			{
				if(m_bluttoothservice.m_blue_state.IsConnected())
				{
					Toast.makeText(context, "连接成功!", Toast.LENGTH_SHORT).show();
					SetListBluetoothconnectState(m_nowItem,BLUE_Connected);
					Intent intent = getIntent();
					setResult(RESULT_OK, intent);
					finish();
				}
				else
				{
					Toast.makeText(context, "连接失败!", Toast.LENGTH_SHORT).show();
					SetListBluetoothconnectState(m_nowItem,BLUE_Connectfail);
				}
			}
			else if(msg.what == HAND_AUTO_CONNECT_BLUETOOTH) //自动连接蓝牙
			{
				AutoExeConnectBlue(m_listdata.get(msg.arg1).get("device_name").toString(), m_listdata.get(msg.arg1).get("device_mac").toString());
			}
		}
	}
	//LIST点击事件，触发进行蓝牙配对


	@Override
	protected synchronized void onDestroy() {
		super.onDestroy();

		// Make sure we're not doing discovery anymore
		if (m_BluetoothAdapter != null) {
			m_BluetoothAdapter.cancelDiscovery();
		}
		//释放蓝牙服务观察者
		if(D) Log.i(TAG,"释放资源!");
		// 释放蓝牙查找接收广播
		this.unregisterReceiver(m_bluetoothReceiver);
	}

	// 初始化接收蓝牙查找广播接收器
	private final BroadcastReceiver m_bluetoothReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent)
		{
			String action = intent.getAction();
			if(D) Log.i(TAG,"接收消息：" + action);
			// 判断查找到了设备
			if (BluetoothDevice.ACTION_FOUND.equals(action))
			{
				//获取设备信息
				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				// 判断如果已经配对则不重复添加列表
				if (device.getBondState() != BluetoothDevice.BOND_BONDED)
				{
					//过滤掉空的蓝牙名
					if(device.getName() == null || (device.getName()).equals("") || (device.getName()).equals("null"))
					{
					}
					else
					{
						//发消息更新列表
						Message msg = m_handler.obtainMessage(HAND_ADD_LIST,device);
						m_handler.sendMessage(msg);
					}
				}
				else //处理搜索到已经配对的设备
				{
					//发消息更新已经配对的蓝牙信号状态
					Message msg = m_handler.obtainMessage(HAND_UPDATE_BAUND_BLUETOOTH,device);
					m_handler.sendMessage(msg);
				}

			} //当查找结束后重置状态
			else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
			{
				//屏蔽查找按钮
				if(D) Log.e(TAG,"查找结束");
				m_but_search.setClickable(true);
				m_but_search.setText(R.string.bluetoothconnect_button_search);
			}
			//蓝牙状态改变
			else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action))
			{
				//获取设备信息
				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				HashMap<String, Object> now = null; //数据源
				//查找设备列表位置
				for(int i = 0; i < m_listadapter.getCount(); i ++)
				{
					now = (HashMap<String, Object>) m_listadapter.getItem(i);
					if((now.get("device_mac").toString()).equals((device.getAddress().toString())))
					{
						if(device.getBondState() == BluetoothDevice.BOND_BONDED)
						{
							now.put("device_pair", getString(R.string.bluetoothconnect_pair));
							//配对完成
							SetListBluetoothconnectState(m_nowItem,BLUE_None);
							CheckBluetoothBox(device.getName(),device.getAddress());
						}
						else
							now.put("device_pair", getString(R.string.bluetoothconnect_nopair));
						break;
					}
				}
				m_listadapter.notifyDataSetChanged();
			}

		}
	};
	//定义List类
	static class DeviceList
	{
		private ImageView Pdevice_icon;  	//设备图标
		private TextView  Pdevice_name;  	//设备名称
		private TextView  Pdevice_status;	//连接状态提示
		private TextView  Pdevice_mac;		//设备mac地址
		private TextView  Pdevice_pair;		//设备配对状态
	}
	//自定义adapter适配器
	class DeviceListAdapter extends BaseAdapter{
		private List<HashMap<String, Object>> mydata = null; //数据源
		private LayoutInflater mInflater = null;
		//构造方法
		public DeviceListAdapter(List<HashMap<String, Object>> listdata) {
			// TODO Auto-generated constructor stub
			mydata = listdata;
			mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mydata.size();
		}
		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			if (mydata != null && mydata.size() > 0)
			{

				return mydata.get(position);
			}
			else
			{
				return null;
			}
		}
		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			DeviceList listview = null;

			if(convertView == null)
			{
				//导入布局
				convertView = mInflater.inflate(R.layout.bluetooth_device_list_item, null);
				//获得列表ITEM对象
				listview = new DeviceList();
				listview.Pdevice_icon = (ImageView)convertView.findViewById(R.id.bluetooth_connect_listitem_image);
				listview.Pdevice_name = (TextView)convertView.findViewById(R.id.bluetooth_connect_listitem_name);
				listview.Pdevice_status = (TextView)convertView.findViewById(R.id.bluetooth_connect_listitem_connectstatus);
				listview.Pdevice_mac = (TextView)convertView.findViewById(R.id.bluetooth_connect_listitem_macaddr);
				listview.Pdevice_pair = (TextView)convertView.findViewById(R.id.bluetooth_connect_listitem_pair);
				//为view设置标签
				convertView.setTag(listview);
			}
			else
			{
				// 取出listview
				listview = (DeviceList)convertView.getTag();
			}
			//传递参数
			listview.Pdevice_icon.setImageResource((Integer) mydata.get(position).get("device_icon"));
			listview.Pdevice_name.setText((String)mydata.get(position).get("device_name"));
			listview.Pdevice_status.setText((String)mydata.get(position).get("device_status"));
			listview.Pdevice_mac.setText((String)mydata.get(position).get("device_mac"));
			listview.Pdevice_pair.setText((String)mydata.get(position).get("device_pair"));
			//if(D) Log.e(TAG,"布局position = "+position+"name:" + (String)mydata.get(position).get("device_name"));

			return convertView;
		}

	}

	//增加名字过滤，只显示launch和DBS开头的蓝牙
	boolean FilterBluetoothName(String bluename)
	{
		if(bluename.indexOf("3301") >= 0 || bluename.indexOf("8801") >= 0)
			return true;
		else
			return false;
	}
	//增加重复查找的列表显示，过滤重复的设备名,查找到则返回成功
	boolean FilterDuplicateName(List<HashMap<String,Object>> list,String macname)
	{
		if(list == null)
			return false;
		for(int i = 0; i < list.size(); i ++)
		{
			HashMap<String, Object> v_data = list.get(i);
			if(v_data.get("device_mac").toString().equals(macname))
				return true;
		}
		return false;
	}
}
